#include "result_pkg.h"
#include "assert.h"
#include <string>
#include "const.h"
#include "log_mgr.h"

ResultPkg::ResultPkg()
:m_dwErrno(0)
{
	m_pErrorMap = new BitMap(2000);
	assert(m_pErrorMap);

	for(int i=0; errorInfo[i]!=NIL; i++)
	{
		m_pErrorMap->On(errorInfo[i]);
	}
}

ResultPkg::~ResultPkg()
{
	delete m_pErrorMap;
}

Result ResultPkg::Parse(Context* pCtx)
{
	//assert(pCtx->pMysql->proto == RESP_QUERY);
	assert(pCtx->pMysql->pBuff);
	
	int iPkgLen = PKG_LEN(pCtx->pMysql->pBuff);
	Result ret = OK;
	
	if(pCtx->pMysql->dwLastRespSize == MAX_PKG_LEN)
	{
		//part of big pkg, dont check pkg head
		pCtx->pMysql->dwLastRespSize = iPkgLen;
	}
	else
	{
		//do check result code
		uint8_t error = *(pCtx->pMysql->pBuff+PKG_HEAD_LEN);
		if(error == MY_SQL_ERROR)
		{
			m_dwErrno = RESULT_SET_ERRNO(pCtx->pMysql->pBuff);
			//check errno, do switch
			ret = this->Check(pCtx);
			if(ret != OK)
				return ret;
			
			PKG("[%s] [RESULT] [errno:%u]", 
				retDesc[ret], 
				m_dwErrno);
		}		
		else
			m_dwErrno = 0;
			
		pCtx->pMysql->dwLastRespSize = iPkgLen;
	}

	return ret;
}

Result ResultPkg::Check(Context* pCtx)
{
	Result ret = OK;

	if(m_pErrorMap->IsOn(m_dwErrno))
	{
		ret = ERR_SWITCH;
		PKG_ERROR("[%s] [result pkg|return critical error ,errno:%u]", 
			retDesc[ret], m_dwErrno);
		return ret;
	}
	
	return ret;
}


